//
//  Heart24Model.swift
//  MoYoung
//
//  Created by sylar on 2017/7/29.
//  Copyright © 2017年 sylar. All rights reserved.
//

/// 实时心率

import Foundation
import SQLite
import SwiftDate
import HandyJSON
import MYModule


open class HeartRateModel: NSObject, MYSQLiteTableiabe, FullDaySQLite, HandyJSON {
    
    public var adress: String = ""
    
    public var id: Int64 = 0
    
    public var date: Date = Date().sqlDate()
    
    public var hearts: [Int] = []
    
    public var updateTime: Double = 0
    
    public var isEmpty: Bool {
        return hearts.filter { $0 > 0 }.isEmpty
    }
    
    

    public var avg: Int {
        
        var avg = 0
        let hearts = hearts.filter { $0 > 0 && $0 < 255 }
       
        if hearts.isEmpty {
            return 0
        }
        avg = hearts.reduce(0, { $0 + $1 })/hearts.count
        return avg
        
    }
    
    public var max: Int {
        var max = 0
        hearts.forEach {
            if max < $0 && $0 < 255 {
                max = $0
            }
        }
        
        return max
    }
    
    public var min: Int {
        
        var minValue = 255
        hearts.forEach {
            if $0 > 0 {
                minValue = Swift.min(minValue, $0)
            }
        }
        
        if minValue == 255 {
            minValue = 0
        }
        
        
        return minValue
    }
    
    /// 多少分钟一个心率
    public var aHeartRateMinute: Int {
        
        // 计算出多少分钟一个心率数据
        if hearts.isEmpty {
            return 0
        }
        let aminute = (24 * 60)/hearts.count
        return aminute
    }
    
    
    /// 每一分钟的实时心率
    public var flatMapWithMinutes: [Int] {
        
        var allHeartRates = (0 ..< 1440).map { _ in  0 }
        
        let space = aHeartRateMinute
        
        for (i, h) in hearts.enumerated() {
            let index = space * i
            allHeartRates[index] = h
            
        }
        
        return allHeartRates
        
    }
    
    
    
    /// 获取心率带类型的数组(一天 48 个, 不包括运动)
    /// - Returns: 详情数组
    public func heartRateDetailModels() ->[HeartRateDetailModel] {
        
        // 心率总 48个
        let allHeartRate = self.hearts
        
        let details = HeartRateDetailModel.detailModels(sqlLiteDatas: allHeartRate, date: date, minute: 30)
        
        return details
    }
    
    
    required public override init() {
        super.init()
    }
    
    
    public func updateData() {
        
        let model = HeartRateModel.day(date: date)
        guard let _ = model else {
            self.insert()
            return
        }
        
        self.update()
        
    }
    
    
    public static func getHeart24ForSleep(date: Date) ->[HeartRateModel] {
        
        let date = date.sqlDate()
        let yesterDate = date - 1.days
        
        var todyModel: HeartRateModel = HeartRateModel()
        todyModel.date = date
        
        var yesterModel: HeartRateModel = HeartRateModel()
        todyModel.date = yesterDate
        
        if let model = HeartRateModel.day(date: date) {
            let tuple = SleepModel.sleepTimeDataMapToTuple(datas: model.hearts, sleepDate: date, minute: 30)
            model.hearts = tuple.morningWakeUp
            todyModel = model
        }
        
        if let model = HeartRateModel.day(date: yesterDate) {
            let tuple = SleepModel.sleepTimeDataMapToTuple(datas: model.hearts, sleepDate: date, minute: 30)
            model.hearts = tuple.tonightFallASleep
            yesterModel = model
        }
        return [yesterModel, todyModel]
        
    }
    

}

public enum HeartRateType {
    
    case dayTime
    case sleeping
    case training
    
}

public struct HeartRateDetailModel {
    
    public var minute: Int
    public var type: HeartRateType
    /// 一分钟内心率最大值
    public var maxHeartRate: Int
    /// 一分钟中内心率最小值
    public var minHeartRate: Int
    /// 一分钟内心率平均值
    public var avgHeartRate: Int
    
}

extension HeartRateDetailModel {
    
    
    public static func detailModels(sqlLiteDatas: [Int], date: Date,  minute compent: Int) -> [HeartRateDetailModel] {
        
        
         // 今日的，零时到醒来时间
        let todaySleepHeartRates = SleepModel.sleepTimeDataMapToTuple(datas: sqlLiteDatas, sleepDate: date, minute: compent)
        
        var all: [HeartRateDetailModel] = []
        var count = 0
        
        let todaySleepsBeforeDetails = todaySleepHeartRates.morningSleep.enumerated().map { i, heartRate -> HeartRateDetailModel in
            
            let type: HeartRateType = .dayTime
    
           let detail = HeartRateDetailModel(minute: i * compent, type: type, maxHeartRate: heartRate, minHeartRate: heartRate, avgHeartRate: heartRate)
            count += 1
            return detail
        }
        
        let todaySleepsDetails = todaySleepHeartRates.morningWakeUp.enumerated().map { i, heartRate -> HeartRateDetailModel in
            
            let type: HeartRateType = .sleeping
    
           let detail = HeartRateDetailModel(minute: i * compent, type: type, maxHeartRate: heartRate, minHeartRate: heartRate, avgHeartRate: heartRate)
            count += 1
            return detail
        }
        let todayDailyDetails = todaySleepHeartRates.daily.enumerated().map { i, heartRate -> HeartRateDetailModel in
            
            let type: HeartRateType = .dayTime
            
           let detail = HeartRateDetailModel(minute: (count + i) * compent, type: type, maxHeartRate: heartRate, minHeartRate: heartRate, avgHeartRate: heartRate)
            count += 1
            return detail
        }
        
        let tomorrowSleepsDetails = todaySleepHeartRates.tonightFallASleep.enumerated().map { i, heartRate -> HeartRateDetailModel in
            
            let type: HeartRateType = .sleeping
           
           return HeartRateDetailModel(minute: (count + i) * compent, type: type, maxHeartRate: heartRate, minHeartRate: heartRate, avgHeartRate: heartRate)
        }
        
        all.append(contentsOf: todaySleepsBeforeDetails)
        all.append(contentsOf: todaySleepsDetails)
        all.append(contentsOf: todayDailyDetails)
        all.append(contentsOf: tomorrowSleepsDetails)
        
        return all
        
    }
    
    
    
}





